package com.lch.netty.bio.tomcat;

import com.lch.netty.bio.tomcat.http.Request;
import com.lch.netty.bio.tomcat.http.Response;
import com.lch.netty.bio.tomcat.http.Servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * 手写tomcat
 *
 * @author: liuchenhui
 * @create: 2019-10-14 11:26
 **/
public class Tomcat {

    /**
     * 1、解析xml(properties)文件，获取url与类实例的map 2、开启监听8080端口的ServerSocket 3、接收到浏览器的请求，并创建request,response
     * 4、通过request中的url找到服务 5、处理逻辑，通过response返回数据
     */

    private int port = 8080;
//    private Properties properties = new Properties();
//    private Map<String, Servlet> xmlMap = new HashMap<>();

    public Tomcat(int port) {
        this.port = port;
    }

    public Tomcat init() throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
//        String path = this.getClass().getResource("/").getPath();
//        FileInputStream fileInputStream = new FileInputStream(path + "tomcat.properties");
//        properties.load(fileInputStream);

//        Set<Object> objects = properties.keySet();
//        for (Object k : objects) {
//            String kStr = (String) k;
//            if (!kStr.endsWith("url")) {
//                continue;
//            }
//            String serverName = kStr.replace(".url", "");
//            String url = properties.getProperty(kStr);
//            String serverClass = properties.getProperty(serverName + ".servlet");
//            xmlMap.put(url, (Servlet) Class.forName(serverClass).newInstance());
//        }
        return this;
    }

    public void start() throws IOException {
        ServerSocket serverSocket = new ServerSocket(this.port);
        System.out.println("tomcat已启动，开始监听" + port + "端口");
        while (true) {
            Socket socket = serverSocket.accept();
            new Thread(() -> {
                try {
                    InputStream inputStream = socket.getInputStream();
                    OutputStream outputStream = socket.getOutputStream();
                    Request request = new Request(inputStream);
                    Response response = new Response(outputStream);
                    porcess(request, response);

                    inputStream.close();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

    /**
     *
     */
    private void porcess(Request request, Response response) throws IOException {
        String url = request.getUrl();
//        if (xmlMap.containsKey(url)) {
//            xmlMap.get(url).services(request, response);
//        } else {
        //用的是HTTP协议，输出也要遵循HTTP协议
        //给到一个状态码 200

        String initCmd =
                "GET OPTION FROM:CEXA191760070\n" + //deviceId
                        "ATTLOGStamp=0\n" + //
                        "OPERLOGStamp=0\n" +
                        "ATTPHOTOStamp=0\n" +
                        "ErrorDelay=30\n" +
                        "Delay=10\n" +
                        "TransFlag=TransData AttLog\tOpLog\tFACE\tChgUser\tChgFP\tEnrollFP\tEnrollUser\n" +
                        "TimeZone=8\n" +
                        "Encrypt=None\n" +
                        "Realtime=1\n" +
                        "PushProtVer=2.4.0";

        StringBuilder sb = new StringBuilder();
        sb.append("HTTP/1.1 200 OK\n")
                .append("Server: nginx/1.6.0\n")
                .append("Date: Tue, 30 Jun 2015 01:24:26 GMT\n")
                .append("Content-Type: text/plain\n")
                .append("Connection: close\n")
                .append("Pragma: no-cache\n")
                .append("Cache-Control: no-store\n")
                .append("\r\n")
                .append("OK");


        OutputStream outputStream = response.getOutputStream();
        outputStream.write(sb.toString().getBytes());
        outputStream.close();
//        }
    }

    public static void main(String[] args) throws Exception {
        Tomcat tomcat = new Tomcat(8088).init();

        tomcat.start();
    }
}
